package com.sinog.front.controller.biz;

import com.sinog.core.model.UploadAppendixFile;
import com.sinog.core.model.UserDTO;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.IdGen;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import com.sinog.front.config.log.Log;
import com.sinog.front.service.azbj.uploadappendix.UploadAppendixFileService;
import com.sinog.front.service.user.UserFacade;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc 上传文件
 * @author -
 * @date -
 */
@Slf4j
@RestController
public class UploadAppendixFileController {

    @Autowired
    private UploadAppendixFileService uploadAppendixService;
    @Autowired
    private UserFacade userFacade;
    private static final String WIN_STR = "win";

    /**
     * 查询流程中上传表单所有服务器端文件
     * @param pageIndex pageIndex
     * @param pageSize pageSize
     * @param taskId taskId
     * @param priNum priNum
     * @param id id
     * @return String
     */
    @GetMapping("/upload/selectAppendixFile/all")
    public String selectAllFile(Integer pageIndex,Integer pageSize,String taskId,String priNum,String id) {
        Map<String,Object> map = new HashMap<>(16);
        map.put("taskId",taskId);
        map.put("priNum",priNum);
        map.put("id",id);
        List<UploadAppendixFile> list = uploadAppendixService.selectAllAppendixFile(pageIndex,pageSize,map);
        return JsonUtil.toText(list.size(),list);
    }

    /**
     * 上传文件 /上传头像指纹、改造表现附件、心理健康附件、是否再犯罪评估附件、刑满释放人员通知书、司法所上传衔接证据、公安附件、二次衔接上报监狱上传附件、设置帮教小组上传附件、户籍地迁出审批附件、安置附件、救助6个附件、帮教6个附件、双列管4个附件、通知公告、帮教资料附件、政策文件附件、经验推介附件、
     * @param request request
     * @param file file
     * @param id id
     * @param priNum priNum
     * @param taskId taskId
     * @return Result
     */
    @Log(type = "新增", value = "上传文件")
    @PostMapping("/upload/uploadAppendixFile/save")
    public Result fileUpload(HttpServletRequest request,@RequestParam("uploadFile") MultipartFile file,String id,String priNum,String taskId) {
        String singleId = IdGen.strid();
        return uploadAppendixService.saveAppendixFile(file,id,priNum,taskId,singleId);
    }

    /**
     * 文件下载 /下载头像指纹、改造表现附件、心理健康附件、是否再犯罪评估附件、刑满释放人员通知书、司法所上传衔接证据、公安附件、二次衔接上报监狱上传附件、设置帮教小组上传附件、户籍地迁出审批附件、安置附件、救助6个附件、帮教6个附件、双列管4个附件、通知公告、帮教资料附件、政策文件附件、经验推介附件、
     * @param request request
     * @param resp resp
     * @param fileUrl fileUrl
     */
    @RequestMapping("/upload/downloadAppendixFile")
    public void downloadFile(HttpServletRequest request,HttpServletResponse resp,String fileUrl) {
        PrintWriter writer;
        boolean containsChar;
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith(WIN_STR)) {
            containsChar = !fileUrl.contains("\\");
        } else {
            containsChar = !fileUrl.contains("/");
        }
        boolean fileUrlBoolean = StringUtils.isBlank(fileUrl) || containsChar || !fileUrl.contains(".");
        if(fileUrlBoolean) {
            try {
                resp.setContentType("text/html; charset=utf-8");
                writer = resp.getWriter();
                writer.println("<script type=\"text/javascript\">alert('请求不合法');window.history.back(-1);</script>");
                writer.flush();
                return;
            } catch(IOException e) {
                log.error("请求不合法:{}",e.getMessage());
                return;
            }
        }
        uploadAppendixService.downloadAppendixFile(request,resp,fileUrl,"1");
    }

    /**
     * 批量下载文件 /批量下载头像指纹、改造表现附件、心理健康附件、是否再犯罪评估附件、刑满释放人员通知书、司法所上传衔接证据、公安附件、二次衔接上报监狱上传附件、设置帮教小组上传附件、户籍地迁出审批附件、安置附件、救助6个附件、帮教6个附件、双列管4个附件、通知公告、帮教资料附件、政策文件附件、经验推介附件、
     * @param resp resp
     * @param request request
     * @param data data
     */
    @RequestMapping("/upload/downloadAppendixFile/all")
    public void downloadAllFile(HttpServletResponse resp,HttpServletRequest request,String data) {
        List<UploadAppendixFile> uploadAppendixFiles = JsonUtil.toList(data,UploadAppendixFile.class);
        if(!uploadAppendixFiles.isEmpty()) {
            uploadAppendixService.downloadAppendixAllFile(resp,request,uploadAppendixFiles,"1");
        }
    }

    /**
     * 删除上传文件 /删除头像、指纹、改造表现附件、心理健康附件、是否再犯罪评估附件、刑满释放人员通知书、司法所上传衔接证据、公安附件、二次衔接上报监狱上传附件、设置帮教小组上传附件、户籍地迁出审批附件、安置附件、救助6个附件、帮教6个附件、双列管4个附件、通知公告、帮教资料附件、政策文件附件、经验推介附件、
     * @param request request
     * @param singleId singleId
     * @param fileUrl fileUrl
     * @param priNum priNum
     * @return Result
     */
    @Log(type = "删除", value = "删除上传文件")
    @DeleteMapping("/upload/uploadAppendixFile/delete/{singleId}")
    public Result deleteSolution(HttpServletRequest request,
                                 @PathVariable String singleId,
                                 @RequestParam("fileUrl") String fileUrl,@RequestParam("priNum") String priNum) {
        String account = userFacade.getAuthentication().getAccount();
        return uploadAppendixService.deleteAppendixFileOne(singleId,fileUrl,account,priNum);
    }

    /**
     * 查询文件的数量
     * @param priNum 罪犯编号
     * @param taskId 文件标识
     * @return Result 文件的数量
     */
    @RequestMapping("/upload/downloadAppendixFile/getCountall")
    public Result getCountAll(@RequestParam("priNum")String priNum,
                              @RequestParam("taskId")String taskId){
        return uploadAppendixService.getCountAll(priNum,taskId);
    }

    /**
     * 根据id priNum taskId查询上传文件数量
     * @param priNum 罪犯编号
     * @param id 随机id
     * @param taskId 业务标识
     * @return Result
     */
    @RequestMapping("/upload/downloadAppendixFile/getCountById")
    public Result getCountById(@RequestParam("priNum")String priNum,@RequestParam("id")String id,@RequestParam("taskId")String taskId){
        return uploadAppendixService.getCountById(priNum, id, taskId);
    }

    /**
     * 根据id priNum taskId删除单个上传文件
     * @param priNum 犯罪编号
     * @param id 唯一id
     * @param taskId 业务标识
     * @return Result
     */
    @RequestMapping("/upload/downloadAppendixFile/deleteById")
    public Result deleteById(@RequestParam String priNum,@RequestParam String id,@RequestParam String taskId){
        return uploadAppendixService.deleteById(priNum, id, taskId);
    }

    /**
     * 视频文件上传
     * @param request request
     * @param response response
     * @return Result
     */
    @Log(type = "新增", value = "上传视频文件")
    @PostMapping("/azbj/spgl/upload")
    public Result uploadVideo(HttpServletRequest request,HttpServletResponse response){
        return uploadAppendixService.uploadFileToFtpRemote(request,response);
    }

    /**
     * 删除视频文件
     * @param request  request
     * @param param 文件名称
     * @return Result
     */
    @Log(type = "删除", value = "删除视频文件")
    @PostMapping("/azbj/spgl/deleteVideo")
    public Result deleteVideo(HttpServletRequest request,@RequestBody Map<String,String> param){
        String name = param.get("name");
        return uploadAppendixService.deleteLocalFile(name);
    }
    /**
     * 系统支持，文件查看和下载（视频）
     * @param request request
     * @param response response
     * @param fileName 视频名称
     * @throws IOException
     */
    @Log(type = "查看", value = "系统支持")
    @GetMapping("/azbj/spgl/download")
    public void downLoadFile(HttpServletRequest request,HttpServletResponse response,String fileName) throws IOException {
        uploadAppendixService.downloadVideo(request,response,fileName);
    }

    /**
     * 查询视频文件
     * @param request request
     * @return String
     *
     */
    @Log(type = "查询", value = "查询视频文件")
    @GetMapping("/azbj/spgl/getAllVideos")
    public String getLoadFiles(HttpServletRequest request,@RequestParam("flag")String flag){
        UserDTO userDTO = userFacade.getAuthentication();
        if (Constants.RoleId.ROLE_ID_AB.equals(userDTO.getRoleid())) {
            return uploadAppendixService.selectAllVideos(flag);
        }
        return ReturnCode.NO_PERMISSION.message();
    }

    /**
     * 更改视频文件状态
     * @param request request
     * @param param 文件名称和状态
     * @return
     */
    @Log(type = "更改", value = "更改视频文件状态")
    @PostMapping("/azbj/spgl/updateVideo")
    public Result updateLoadFiles(HttpServletRequest request,@RequestBody Map<String,String> param){
        String name = param.get("name");
        String status = param.get("status");
        return uploadAppendixService.updateStatus(name,status);
    }
}